#include "../include/AT91SAM7S64.h"					// Register-Definitionen

#include "hardware/serial.h"
#include "hardware/io.h"

#include "comm/comm.h"

#include "config.h"


#include <stdlib.h>

#define LOOPBLINK 20000
#define LOOPBLINK2 LOOPBLINK/2


unsigned int loopcounter;




volatile int count_timer1_interrupt;

#define TIMER1_INTERRUPT_LEVEL		4


#define TC_CLKS                  0x7
#define TC_CLKS_MCK2             0x0
#define TC_CLKS_MCK8             0x1
#define TC_CLKS_MCK32            0x2
#define TC_CLKS_MCK128           0x3
#define TC_CLKS_MCK1024          0x4



int testData(int lineNum, char *buffer) {
	switch (lineNum) {
		case 0:
			sprintf(buffer, "Loopcount: %d", loopcounter);
			break;
		case 1:
			sprintf(buffer, "Timer Value: %d", AT91C_BASE_TC1->TC_RC);
			break;
		default:
			return 0;
	}
	return 1;
}

 void timer1_c_irq_handler(void)
{
	AT91PS_TC TC_pt = AT91C_BASE_TC1;
    unsigned int dummy;
    //* Acknowledge interrupt status
    dummy = TC_pt->TC_SR;

    //* Suppress warning variable "dummy" was set but never used
    //dummy = dummy;
    count_timer1_interrupt++;

    //* Read the output state
    Comm_sendBefehlData(getSerialSrv(), "clock!", testData, 64);
}

 void AT91F_TC_Open ( AT91PS_TC TC_pt, unsigned int Mode, unsigned int TimerId)
 //* Begin
 {
     unsigned int dummy;

     //* First, enable the clock of the TIMER
     AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
     //	AT91F_PMC_EnablePeriphClock ( AT91C_BASE_PMC, 1<< TimerId ) ;

     //* Disable the clock and the interrupts
 	TC_pt->TC_CCR = AT91C_TC_CLKDIS ;
 	TC_pt->TC_IDR = 0xFFFFFFFF ;

     //* Clear status bit
         dummy = TC_pt->TC_SR;
     //* Suppress warning variable "dummy" was set but never used
      //   dummy = dummy;
     //* Set the Mode of the Timer Counter
 	TC_pt->TC_CMR = Mode ;

     //* Enable the clock
 	TC_pt->TC_CCR = AT91C_TC_CLKEN ;
 //* End
 }

// main: Hauptprogramm
int main(void) {

	io_init();
	comm_init();
/*
	count_timer1_interrupt=0;
	AT91F_TC_Open(AT91C_BASE_TC1,TC_CLKS_MCK32,AT91C_ID_TC1);
	AT91F_AIC_ConfigureIt ( AT91C_BASE_AIC, AT91C_ID_TC1, TIMER1_INTERRUPT_LEVEL,AT91C_AIC_SRCTYPE_INT_EDGE_TRIGGERED, timer1_c_irq_handler);
	AT91C_BASE_TC1->TC_IER  = AT91C_TC_CPCS;  //  IRQ enable CPC
	AT91C_BASE_TC1->TC_RC = 3;
	AT91F_AIC_EnableIt (AT91C_BASE_AIC, AT91C_ID_TC1);
	AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG ;
*/
	while (1){
		if (loopcounter%LOOPBLINK == LOOPBLINK2)
			io_ledon(1);
		if (loopcounter%LOOPBLINK == 0)
			io_ledoff(1);
		loopcounter++;

		if (loopcounter%(LOOPBLINK) == 0) {
			// Comm_sendBefehlData(getSerialSrv(), "STATUS", testData, 64);
			//	 Comm_sendBefehlData(getBluetoothSrv() , "STATUS", testData, 64);
		}

		comm_cycle();

	}
}
